import QtQuick 2.0

MouseArea{
    id: root
    property vector2d pressedVec        //按下点
    property vector2d distanceVec       //移动距离
    property int moveThreshold: 200     //滑动距离触发阈值
    property bool showRubberBand: true  //显示橡皮筋特效
    property int startX: 0              //橡皮筋开始x坐标  确定从左往右 还是从右往左
    property int endX: canvasHint.width //橡皮筋结束x坐标
    property color hintColor: Qt.rgba(0,0,0,0.7) //橡皮筋效果颜色

    propagateComposedEvents: true

    //拖到最大值触发信号
    signal backTriggered()
    onPressed: function(mouse){
        console.log("onPressed");
        pressedVec = Qt.vector2d(mouseX,mouseY)
//        mouse.accepted = false
    }
    onReleased: function(mouse){
        console.log("onReleased");
        //检查是否超出阈值
        if(Math.abs(distanceVec.x) > moveThreshold)
            backTriggered();

        pressedVec = Qt.vector2d(0,0)
        distanceVec = Qt.vector2d(0,0)

//        if(distanceVec.x < 10)
//            mouse.accepted = false
    }
    onPositionChanged:function(mouse){
        console.log("onPositionChanged");
        var posVec = Qt.vector2d(mouseX,mouseY)
        //计算两点距离
        distanceVec = pressedVec.minus(posVec);
//        mouse.accepted = false
    }


    Rectangle{
        anchors.fill: parent
        color: "#60ff0000"
    }



    Canvas{
        id: canvasHint //拖动提示
        visible: showRubberBand && root.pressed
        width: parent.width
        height: 300
        y: {
            var tmpY = pressedVec.y - height / 2;
            return tmpY < 0 ? 0 : tmpY > parent.height - height ? parent.height - height : tmpY;
        }
        //橡皮筋提示效果宽度
        property real hintWidth: Math.min(width,Math.abs(distanceVec.x) / moveThreshold * width)
        onHintWidthChanged: requestPaint()
        onPaint: {
            var ctx = getContext("2d");
            ctx.fillStyle = hintColor;
            var offsetX = startX < endX ? startX + hintWidth : (startX-endX) - hintWidth; //橡皮筋拉开偏移x
            ctx.clearRect(0,0,width,height);
            ctx.beginPath();
            ctx.moveTo(startX, 0);
            ctx.bezierCurveTo(startX, height * 0.3, offsetX, height * 0.3, offsetX, height/2); //手柄1坐标，手柄2坐标，结束点坐标
            ctx.bezierCurveTo(offsetX, height * 0.7, startX, height * 0.7, startX, height);
            ctx.lineTo(startX,0);
            ctx.fill();
        }
    }
}
